import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Post,
  Request,
  Session,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { Public } from './decorators/public.decorator';

@Controller('/api/auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Public()
  @HttpCode(HttpStatus.OK)
  @Post('login')
  async signIn(
    @Session() session: Record<string, any>,
    @Body() signInDto: Record<string, any>,
  ) {
    console.log('登录成功', signInDto);
    const { captcha } = signInDto;
    const sessionCaptcha = session.captcha; // 在会话中的验证码
    console.log('比较时session', session.captcha)
    // 验证用户输入的验证码是否正确
    console.log('验证码', captcha, sessionCaptcha)
    if (!this.authService.verifyCaptcha(captcha, sessionCaptcha)) {
      return {
        code: 1000,
        data: null,
        message: '验证码输入错误',
      };
    }
    const result = await this.authService.signIn(
      signInDto.username,
      signInDto.password,
    );
    console.log('result', result);
    const access_token = result?.access_token;
    // if (access_token) {
    //   res.cookie('access_token', access_token, {
    //     httpOnly: true, // Increases security by preventing client-side script access
    //     secure: process.env.NODE_ENV !== 'development', // Use HTTPS in production
    //     // other options...
    //   });
    // }
    return {
      code: access_token ? 200 : 1000,
      data: access_token ? result : {},
      message: access_token ? 'ok' : '请检查用户名和密码',
    };
  }

  @Post('logout')
  async logout(@Session() session: Record<string, any>) {
    // session.destroy();
    return {
      code: 0,
      data: {},
      message: '退出成功',
    };
  }

  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }

  @Public()
  @Post('captcha')
  getCaptcha(@Session() session: Record<string, any>) {
    console.log('是否会进入这里')
    // 生成验证码，并保存到会话中
    const captcha = this.authService.generateCaptcha();
    // console.log('---->', captcha.text, session)
    session.captcha = captcha.text; // 将验证码文本保存到会话中，用于后续验证
    console.log('session---->', session)
    return { captcha: captcha.data };
  }
}
